<template>
  <div>
    <!-- 搜索 Begin -->
    <div
      class="bg-[--el-color-primary-light-8] flex flex-justify-center flex-items-center flex-wrap p-x-50px p-y-30px m-b-10px border-1px border-solid border-[--el-border-color-light]"
    >
      <el-input
        v-model="searchParams.articleTitle"
        placeholder="请输入文章标题..."
        clearable
        class="w-80% h-38px text-13px <sm:w-100% <sm:m-b-6px"
        @keyup.enter.native="handleSearch()"
      >
      </el-input>
      <el-button
        class="uppercase tracking-1px w-20% <sm:w-100% h-38px rounded-0 text-#fff bg-#000 hover:bg-#000 text-12px"
        @click="handleSearch"
      >
        Search
      </el-button>
    </div>
    <!-- 搜索 End -->
    <!-- 文章类别 Begin -->
    <div
      v-if="categoryList.length > 0"
      :class="{ 'h-auto': categoryOverflow }"
      class="pos-relative h-56px overflow-hidden m-b-10px p-8px bg-#FAFAFA rounded-4px dark:bg-[rgba(0,0,0,0.3)] border-1px border-solid border-[--el-border-color-light]"
    >
      <div class="flex flex-items-center flex-wrap gap-x-6px gap-y-8px text-16px p-r-36px">
        <div
          class="p-x-10px p-y-5px text-[--el-text-color-primary] border-1px border-solid border-[--el-border-color] hover:text-[--el-color-primary] hover:bg-[rgb(245,245,245)] dark:hover:bg-[rgb(245,245,245,0.07)] rounded-4px whitespace-nowrap select-none transition-all duration-600 transition-ease-in-out"
          style="font-family: Muli, sans-serif"
          v-for="item in categoryList"
          :key="item.categoryId"
          @click="handleCategory(item.categoryId)"
          :class="{
            '!text-#FFF !bg-[--el-color-primary]': item.categoryId == categoryId
          }"
        >
          {{ item.categoryName }}
        </div>
      </div>
      <div class="pos-absolute top-12px right-8px hover:text-[--el-color-primary]">
        <el-button circle @click="handleCategoryOverflow">
          <el-icon v-if="!categoryOverflow">
            <plus />
          </el-icon>
          <el-icon v-else>
            <Minus />
          </el-icon>
        </el-button>
      </div>
    </div>

    <!-- 骨架屏 Begin -->
    <div v-else>
      <el-skeleton animated>
        <template #template>
          <el-skeleton-item class="w-100% h-56px m-b-10px" />
        </template>
      </el-skeleton>  
    </div>
    <!-- 骨架屏 End -->     
    <!-- 文章类别 End -->

    <!-- 文章标签 Begin -->
    <div
      v-if="tagList.length > 0"
      :class="{ 'h-auto': tagOverflow }"
      class="pos-relative h-56px overflow-hidden m-b-10px p-8px bg-#FAFAFA rounded-4px dark:bg-[rgba(0,0,0,0.3)] border-1px border-solid border-[--el-border-color-light]"
    >
      <div class="flex items-center flex-wrap gap-x-6px gap-y-8px text-16px p-r-36px">
        <div
          class="p-x-10px p-y-5px text-[--el-text-color-primary] border-1px border-solid border-[--el-border-color] hover:text-[--el-color-primary] hover:bg-[rgb(245,245,245)] dark:hover:bg-[rgb(245,245,245,0.07)] rounded-4px whitespace-nowrap select-none transition-all duration-600 transition-ease-in-out"
          style="font-family: Muli, sans-serif"
          v-for="item in tagList"
          :key="item.tagId"
          @click="handleTag(item.tagId)"
          :class="{
            '!text-#FFF !bg-[--el-color-primary]': item.tagId == tagId
          }"
        >
          {{ item.tagName }}
        </div>
      </div>
      <div class="pos-absolute top-12px right-8px hover:text-[--el-color-primary]">
        <el-button circle @click="handleTagOverflow">
          <el-icon v-if="!tagOverflow">
            <plus />
          </el-icon>
          <el-icon v-else>
            <Minus />
          </el-icon>
        </el-button>
      </div>
    </div>
    <!-- 骨架屏 Begin -->
    <div v-else>
      <el-skeleton animated>
        <template #template>
          <el-skeleton-item class="w-100% h-56px m-b-10px" />
        </template>
      </el-skeleton>  
    </div>
    <!-- 骨架屏 End --> 
    <!-- 文章标签 End --> 
    <!-- 文章列表布局 Begin -->
    <el-segmented class="m-b-10px" v-model="segmentedValue" :options="segmentedOptions" block @change="handleSegmented" />
    <!-- 文章列表布局 End --> 
    <!-- 文章列表 Begin -->
    <el-row :gutter="27">
      <el-col :xl="12" :lg="12" :md="12" :sm="12" :xs="24" class="m-b-40px" v-for="item in articleList" :key="item.articleId" v-if="segmentedValue === '双列' && articleList.length > 0">
        <div>
          <div class="w-100% h-256px <md:h-360px overflow-hidden m-b-15px">
            <el-image
              :src="item.picture"
              fit="cover"
              class="w-100% h-100% hover:transform-scale-105 transition-all duration-600 ease-in-out"
              @click="handleArticleContent(item.articleId)"
            >
              <template #error>
                <el-image :src="errorUrl" fit="contain" class="w-100% h-100%"></el-image>
              </template>
            </el-image>
          </div>
          <!-- 文章类别 -->
          <div
            class="capitalize text-18px font-700 text-[--el-color-primary] tracking-1px m-b-15px"
            style="font-family: 'Dancing Script', cursive"
          >
            {{ item.categoryName }}
          </div>
          <!-- 文章标签 -->
          <div class="flex line-clamp-1 m-b-6px">
            <div
              v-for="tag in item.tagList"
              :key="tag.tagId"
              class="text-#000 dark:text-#D8D8D8 m-r-3px m-b-3px p-y-5px p-x-10px border-1px border-[--el-color-primary] border-solid rounded-4px text-#000 text-12px hover:text-[--el-color-primary] font-400 tracking-1px line-height-12px transition-all duration-600 transition-ease"
              style="font-family: 'Muli', sans-serif"
            >
              {{ tag.tagName }}
            </div>
          </div>
          <!-- 文章标题 gradient-line -->
          <div
            class="gradient-title capitalize text-#333 text-23px font-700 h-70px line-clamp-2 dark:text-#D8D8D8 hover:text-#606266 dark:hover:text-#9A9A9A"
            style="font-family: 'Open Sans', sans-serif"
            @click="handleArticleContent(item.articleId)"
          >
            <!-- {{ item.articleTitle }} -->
            <div v-html="item.highlightArticleTitle"></div>
          </div>
          <!-- 文章作者 AND 创建时间 -->
          <div
            class="text-center m-y-10px flex flex-row flex-justify-start flex-items-center line-clamp-1"
            style="font-family: 'Muli', sans-serif"
          >
            <div class="border-1px border-solid border-[--el-color-primary] w-34px h-34px p-1px rounded-full m-r-10px flex flex-justify-center flex-items-center">
              <el-image :src="avatarUrl" fit="cover" class="w-30px h-30px rounded-full hover:opacity-70 transition-all duration-600 transition-ease-in-out">
                <template #error>
                  <el-image :src="errorUrl" fit="contain" class="w-30px h-30px rounded-full hover:opacity-70 transition-all duration-600 transition-ease-in-out"></el-image>
                </template>
              </el-image>
            </div>
            <div class="text-13px text-#1D1D1D dark:text-#D8D8D8 hover:text-[--el-color-primary] transition-all duration-600 transition-ease">
              {{ item.createBy }}
            </div>
            <div class="flex flex-justify-center flex-items-center">
              <div class="text-[--el-color-primary] text-12px m-x-3px font-bold">﹣</div>
              <div class="text-13px text-#4B4F56 dark:text-#D8D8D8">{{ item.createTime }}</div>
              <div class="text-[--el-color-primary] text-13px m-x-3px font-bold">﹣</div>
              <div class="text-13px text-#4B4F56 dark:text-#D8D8D8">{{ getFormatToK(item.views) }} Views</div>
            </div>
          </div>
          <!-- 文章描述 -->
          <div class="text-#7E7E7E dark:text-#D8D8D8 text-14px h-46px line-clamp-2">
            {{ item.remark }}
          </div>
          <!-- 阅读更多 -->
          <div
            class="text-12px hover:text-[--el-color-primary] text-#1D1D1D dark:text-#D8D8D8 uppercase tracking-1px font-600 m-t-15px inline-block border-b-solid border-b-1px border-b-[--el-color-primary] transition-all duration-600 transition-ease"
            @click="handleArticleContent(item.articleId)"
          >
            READ MORE
          </div>
        </div>
      </el-col>

      <!-- 文章数据为 0 -->
      <div class="w-100% flex flex-justify-center" v-if="articleList.length == 0 && !articleIsSkeleton">
        <el-empty :image="errorUrl" :image-size="300" description="主人，没有数据了哟👻"></el-empty>
      </div>

      <!-- 骨架屏 Begin -->
      <div class="w-100%" v-if="segmentedValue === '双列' && articleIsSkeleton">
        <el-skeleton animated>
          <template #template>
            <div class="flex flex-wrap flex-justify-center">
              <div class="p-x-15px w-50% flex flex-col flex-justify-between m-b-15px" v-for="(_item, index) in 12" :key="index">
                <el-skeleton-item variant="image" class="w-100% h-256px <md:h-360px m-r-10px m-b-15px" />
                <el-skeleton-item class="w-120px h-26px" />
                <div class="flex flex-row m-y-10px">
                  <el-skeleton-item class="w-75px h-26px m-r-10px" />
                  <el-skeleton-item class="w-100px h-26px" />
                </div>
                <el-skeleton-item class="w-100% h-36px" />
                <div class="flex flex-row flex-items-center m-y-10px">
                  <el-skeleton-item variant="image" class="rounded-full w-30px h-30px m-r-10px" />
                  <el-skeleton-item class="w-200px h-20px" />
                </div>
                <el-skeleton-item class="w-100% h-50px m-b-16px" />
                <el-skeleton-item class="w-120px h-26px m-b-16px" />
              </div>  
            </div>    
          </template>
        </el-skeleton>  
      </div>
      <!-- 骨架屏 End --> 

      <el-col :span="24" class="m-b-40px" v-for="item in articleList" :key="item.articleId" v-if="segmentedValue === '横向' && articleList.length > 0">
        <div class="w-100% flex <md:flex-col">
          <!-- 文章左侧 Begin -->
          <div class="w-48% <md:w-100% h-256px <md:h-360px overflow-hidden m-r-26px">
            <el-image
              :src="item.picture"
              fit="cover"
              class="w-100% h-100% hover:transform-scale-105 transition-all duration-600 ease-in-out"
              @click="handleArticleContent(item.articleId)"
            >
              <template #error>
                <el-image :src="errorUrl" fit="contain" class="w-100% h-100%"></el-image>
              </template>
            </el-image>
          </div>
          <!-- 文章左侧 End -->
          <!-- 文章右侧 Begin -->
          <div class="flex flex-col flex-1 p-y-7px <md:m-t-8px">
            <!-- 文章类别 -->
            <div
              class="capitalize text-18px font-700 text-[--el-color-primary] tracking-1px m-b-8px <md:m-b-15px"
              style="font-family: 'Dancing Script', cursive"
            >
              {{ item.categoryName }}
            </div>
            <!-- 文章标签 -->
            <div class="flex line-clamp-1 m-b-6px">
              <div
                v-for="tag in item.tagList"
                :key="tag.tagId"
                class="text-#000 dark:text-#D8D8D8 m-r-3px m-b-3px p-y-5px p-x-10px border-1px border-[--el-color-primary] border-solid rounded-4px text-#000 text-12px hover:text-[--el-color-primary] font-400 tracking-1px line-height-12px"
                style="font-family: 'Muli', sans-serif"
              >
                {{ tag.tagName }}
              </div>
            </div>
            <!-- 文章标题 gradient-line -->
            <div
              class="gradient-title capitalize text-#333 text-23px font-700 h-70px line-clamp-2 dark:text-#D8D8D8 hover:text-#606266 dark:hover:text-#9A9A9A"
              style="font-family: 'Open Sans', sans-serif"
              @click="handleArticleContent(item.articleId)"
            >
              <!-- {{ item.articleTitle }} -->
              <div v-html="item.highlightArticleTitle"></div>
            </div>
            <!-- 文章作者 AND 创建时间 -->
            <div
              class="text-center m-y-10px flex flex-row flex-justify-start flex-items-center line-clamp-1"
              style="font-family: 'Muli', sans-serif"
            >
              <div class="border-1px border-solid border-[--el-color-primary] w-34px h-34px p-1px rounded-full m-r-10px flex flex-justify-center flex-items-center">
                <el-image :src="avatarUrl" fit="cover" class="w-30px h-30px rounded-full hover:opacity-70 transition-all duration-600 transition-ease-in-out">
                  <template #error>
                    <el-image :src="errorUrl" fit="contain" class="w-30px h-30px rounded-full hover:opacity-70 transition-all duration-600 transition-ease-in-out"></el-image>
                  </template>
                </el-image>
              </div>
              <div class="text-13px text-#1D1D1D dark:text-#D8D8D8">
                {{ item.createBy }}
              </div>
              <div class="flex flex-justify-center flex-items-center">
                <div class="text-[--el-color-primary] text-12px m-x-3px font-bold">﹣</div>
                <div class="text-13px text-#4B4F56 dark:text-#D8D8D8">{{ item.createTime }}</div>
                <div class="text-[--el-color-primary] text-12px m-x-3px font-bold">﹣</div>
                <div class="text-13px text-#4B4F56 dark:text-#D8D8D8">{{ getFormatToK(item.views) }} Views</div>
              </div>
            </div>
            <!-- 文章描述 -->
            <div class="text-#7E7E7E dark:text-#D8D8D8 text-14px h-46px line-clamp-2">
              {{ item.remark }}
            </div>
            <!-- 阅读更多 -->
            <div
              style="width: max-content;"
              class="md:hidden text-12px hover:text-[--el-color-primary] text-#1D1D1D dark:text-#D8D8D8 uppercase tracking-1px font-600 m-t-15px border-b-solid border-b-1px border-b-[--el-color-primary]"
              @click="handleArticleContent(item.articleId)"
            >
              READ MORE
            </div>
          </div>
          <!-- 文章右侧 End -->
        </div>
      </el-col>

      <!-- 骨架屏 Begin -->
      <div class="w-100%" v-if="segmentedValue === '横向' && articleIsSkeleton">
        <el-skeleton animated>
          <template #template>
            <div class="w-100% flex flex-row p-x-15px" v-for="(_item, index) in 12" :key="index">
              <div class="w-45% flex flex-col m-b-15px m-r-26px">
                <el-skeleton-item variant="image" class="w-100% h-256px <md:h-360px m-r-10px m-b-15px" />
              </div>  
              <div class="w-46% p-y-9px">
                <el-skeleton-item class="w-120px h-30px" />
                <div class="flex flex-row m-y-10px">
                  <el-skeleton-item class="w-75px h-26px m-r-10px" />
                  <el-skeleton-item class="w-100px h-26px" />
                </div>
                <el-skeleton-item class="w-100% h-40px" />
                <div class="flex flex-row flex-items-center m-y-10px">
                  <el-skeleton-item variant="image" class="rounded-full w-30px h-30px m-r-10px" />
                  <el-skeleton-item class="w-200px h-20px" />
                </div>
                <el-skeleton-item class="w-100% h-56px" />
              </div>
            </div>    
          </template>
        </el-skeleton>  
      </div>
      <!-- 骨架屏 End -->       
    </el-row>
    <div class="flex flex-justify-center m-t-10px">
      <!-- 分页 -->
      <el-pagination
        background
        :pager-count="5"
        v-model:current-page="searchParams.pageNo"
        v-model:page-size="searchParams.pageSize"
        v-show="total > 0"
        layout="total, prev, pager, next, jumper"
        :total="total"
        @size-change="handleListPage"
        @current-change="handleListPage"
      />
    </div>
    <!-- 文章列表 End -->
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import errorUrl from "@/assets/images/error/404.png";
import { koiMsgWarning, koiNoticeError } from "@/utils/koi.ts";
import { getFormatToK } from "@/utils/index.ts";
import { listPage } from "@/api/blog/article/index.ts";
import { listCategory } from "@/api/blog/category/index.ts";
import { listTag } from "@/api/blog/tag/index.ts";
import { useRoute } from "vue-router";

const route = useRoute();

const avatarUrl = "https://pic3.zhimg.com/80/v2-cb928dab1abe5231fb87db69498de128_720w.webp";

/** 查询参数 */
const searchParams = ref<any>({
  articleTitle: "", // 文章标题
  categoryId: "",
  tagId: "",
  pageNo: 1, // 第几页
  pageSize: 10 // 每页显示多少条
});

const total = ref(100);
const articleList = ref<any>([]);

/** 搜索 */
const handleSearch = () => {
  console.log("搜索");
  searchParams.value.pageNo = 1;
  handleListPage();
};

onMounted(() => {
  handleCategoryData();
  handleTagData();
  handleRouteParams();
  handleListPage();
});


/** 接收页面传递参数 */
const handleRouteParams = () => {
  if (route.params?.type == "category") {
    categoryId.value = route.params?.id;
    searchParams.value.categoryId = categoryId.value;
  } 

  if (route.params?.type == "tag") {
    tagId.value = route.params?.id;
    searchParams.value.tagId = tagId.value;
  }
};

// 骨架屏是否显示[默认关闭]
const articleIsSkeleton = ref(false);

/** 获取文章数据 */
const handleListPage = async () => {
  try {
    articleList.value = [];
    articleIsSkeleton.value = true;
    const res: any = await listPage(searchParams.value);
    console.log("文章数据->", res.data);
    articleList.value = res.data.records;
    total.value = res.data.total;
    if (articleList.value.length > 0) {
      articleList.value = res.data.records.map((item: any) => ({
        ...item,
        highlightArticleTitle: highlightText(item.articleTitle, searchParams.value.articleTitle),
      }));
    }
    articleIsSkeleton.value = false;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试🌻");
  }
};

/** 高亮文本 */
const highlightText = (text: any, keyword: any) => {
  if (!text || !keyword) return text;

  // 转义特殊字符
  const escapedKeyword = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

  // 创建正则表达式，忽略大小写
  const regex = new RegExp(`(${escapedKeyword})`, 'gi');

  // 使用 font 标签包裹关键词
  return text.replace(regex, '<font style="color: var(--el-color-primary) !important;">' + keyword + '</font>');
};

// 类别卡片
const categoryOverflow = ref(false);
const handleCategoryOverflow = () => {
  categoryOverflow.value = !categoryOverflow.value;
};

const categoryList = ref<any>([]);

/** 获取文章类别数据 */
const handleCategoryData = async () => {
  try {
    categoryList.value = [];
    const res: any = await listCategory("categoryName");
    console.log("文章类别数据->", res.data.categoryList);
    let newCategory = { categoryId: 0, categoryName: "Full" };
    categoryList.value = [newCategory, ...res.data.categoryList];
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试🌻");
  }
};

const categoryId = ref<any>(0);

/** 点击文章类别 */
const handleCategory = (value: any) => {
  categoryId.value = value;
  if (value == 0) {
    searchParams.value.categoryId = null;
  } else {
    searchParams.value.categoryId = value;
  }
  handleListPage();
};

// 标签卡片
const tagOverflow = ref(false);

const handleTagOverflow = () => {
  tagOverflow.value = !tagOverflow.value;
};

const tagList = ref<any>([]);

/** 获取文章标签数据 */
const handleTagData = async () => {
  try {
    tagList.value = [];
    const res: any = await listTag();
    console.log("文章标签数据->", res.data);
    let newTag = { tagId: 0, tagName: "Full" };
    tagList.value = [newTag, ...res.data];
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试🌻");
  }
};

const tagId = ref<any>(0);

/** 点击文章标签 */
const handleTag = (value: any) => {
  tagId.value = value;
  if (value == 0) {
    searchParams.value.tagId = null;
  } else {
    searchParams.value.tagId = value;
  }
  handleListPage();
};

const segmentedValue = ref("双列")

const segmentedOptions = [
  "双列",
  "横向"
];

/** 点击切换布局 */
const handleSegmented = (value: any) => {
  segmentedValue.value = value;
};

/** 文章内容 */
const handleArticleContent = (articleId: any) => {
  if (articleId) {
    console.log("文章内容->", articleId);
    // 方式一：本地项目路由跳转
    // / 参数形式，需要在staticRouter中配置，使用 route.params.articleId 接收参数
    // router.push({ path: `/article/content/${articleId}/${articleTitle}` });
    // ? 参数形式，使用 route.query.articleId 接收参数
    // router.push({ path: `/article/content`, query: { articleId, articleTitle } });

    // 方式二：新标签
    window.open(`/article/content/${articleId}`, "_blank");
  } else {
    koiMsgWarning("未获取文章参数，请刷新页面重试");
  }
};
</script>

<style scoped></style>
